<template>
  <div class="header-title">
    <div style="margin-right: 30px">
      <el-link type="primary" @click="barkList">返回列表</el-link>
    </div>
    <div class="header-item">
      <span style="font-weight: bold">表单名称：</span>
      <el-input v-model="templateName" style="width: 240px" placeholder="请输入" />
    </div>
    <div class="header-item" style="margin-left: 30px">
      <span style="font-weight: bold">证件类型：</span>
      <el-select v-model="cardType" placeholder="请选择" size="large" style="width: 240px">
        <el-option v-for="item in cardTypeList" :key="item.id" :label="item.cnName" :value="item.id"/>
      </el-select>
    </div>
  </div>
  <div class="form-box">
    <div class="form-fields">
<!--      <el-checkbox-group style="display: flex;flex-wrap: wrap" v-model="fieldsCheckList" @change="change">
        <el-checkbox-button style="margin: 0 0 10px 10px;width: 150px" v-for="item in fields" :label="item.label" :value="item.value" />
      </el-checkbox-group>-->
      <div class="form-fields-item" v-for="(item,index) in fields.value" :key="item.id" :style="{ backgroundColor: item.select ? '#cccccc' :'#ffffff'}" @click="selectFieldsClick(item)" @dblclick="selectFields(item,index)">{{ item.beiZhu }}</div>
    </div>
    <div class="form-body form-set-body-box">
      <FormCreate :rule="rule.data" :option="options" v-model="formData" v-model:api="fApi"></FormCreate>
    </div>
    <div class="form-config">
      <div v-if="currField.effect">
        <div class="form-config-item">
          <span>字段名称:{{currField.title}}</span>
        </div>
        <div class="form-config-item">
          <span>字段别名:{{currField.field}}</span>
        </div>
        <div class="form-config-item">
          <span>必填:</span>
          <el-switch v-model="currField.effect.required" @change="switchChange" />
        </div>
      </div>
    </div>
  </div>
  <div style="margin-top: 30px;text-align: center;">
    <el-button type="primary" @click="saveTemplate">保存模板</el-button>
  </div>
</template>
<script setup>
import { compress, compressAccurately } from 'image-conversion'
import {Address} from '../../assets/province_city_area.json';
//导入 form-create
import formCreate from "@form-create/element-ui";
import {ref,reactive,onMounted} from "vue";
import {
  _addTemplate,
  _getCardTypeList, _getFieldList,
  _getFormInfoById, _getOptionListByName,
  _updateForm
} from "../../http/api.js";
import { useRoute,useRouter} from "vue-router";
import {ElLoading, ElMessage,ElMessageBox} from "element-plus";
import { addField } from '../../utils/field'

const route = useRoute()
const router = useRouter()
const id = route.query.id;
console.log(Address);
//获取 formCreate 组件
const FormCreate = formCreate.$form();
const fApi = ref({});
const formData = ref({});
const options = ref({
  //表单提交事件
  submitBtn: false,
  form:{
    labelWidth: '200px'
  }
});
const templateName = ref(''); // 表单名称
const cardType = ref(''); // 选择的证件类型
const cardTypeList = ref([]); // 证件类型列表
const fields = reactive({
  value:[]
})

// 选择的字段
const rule = reactive({
  data:[]
})
// 当前选择的字段
const currField = ref({});
const clickTimeout = ref(null);

// 返回列表
const barkList = () => {
  router.go(-1)
}
//获取证件类型列表
const getCardTypeList = () => {
  _getCardTypeList(1,1000)
      .then(res => {
        console.log(res);
        if(res.data.ok){
          cardTypeList.value = res.data.data.records;
        }
      })
      .catch(err => {
        console.log(err);
      })
}
getCardTypeList()
// 获取字段列表
const getFieldList = () => {
  let params = {current: 1, size: 1000}
  _getFieldList(params)
      .then(res => {
        console.log(res);
        if(res.data.ok) {
          let item = res.data.data;
          fields.value = item.records;
          let types = [];
          fields.value.forEach((v,i) => {
            fields.value[i]['select'] = false;
            if(v.fieldType === 'select' || v.fieldType === 'radio') {
              types.push(v.fieldName)
            }
          })
          getOptionListByName(types.toString())
        }
      })
      .catch(err => {
        console.log(err);
      })
}
getFieldList();
// 获取字段列表二级选项
const getOptionListByName = (type) => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  _getOptionListByName(type)
      .then(res => {
        console.log(res);
        loading.close();
        if(res.data.ok) {
          let arr = res.data.data;
          console.log(arr);
          for (let j = 0; j < arr.length; j++) {
            for (let i = 0; i < fields.value.length; i++) {
              if(arr[j].fieldType === fields.value[i].fieldName) {
                let list = arr[j].list||[];
                let arrList = [];
                list.forEach(v => {
                  arrList.push({ label: v.name,value: v.value })
                })
                fields.value[i]['optionsData'] = arrList;
              }
            }
          }
          if(id) {
            getInfoById()
          }
        }
      })
      .catch(err => {
        console.log(err);
        loading.close();
        ElMessage({message: '网络异常', type: 'error' });
      })
}
//字段选择 双击
const selectFields = (item,index) => {
  console.log(item);
  clearTimeout(clickTimeout.value);
  let { fieldName,fieldType,notes,notesEn,optionsData, select } = item;
  if(select) {
    for (let i = 0; i < rule.data.length; i++) {
      if(rule.data[i].field === fieldName) {
        rule.data.splice(i,1);
      }
    }
    fields.value[index].select = false;
    fApi.value.refreshOptions();
  }else {
    let cardTypeSelect = cardTypeList.value.filter(v => v.id === cardType.value);
    let title = notes;
    if(cardTypeSelect && cardTypeSelect.length && cardTypeSelect[0].cnName === 'IOC证件') {
      title = notesEn;
    }
    let config = addField(fieldType,{field:fieldName,title},optionsData);
    rule.data.push(config);
    fields.value[index].select = true;
    currField.value = { ... config };
  }
}
// 字段选择 单击
const selectFieldsClick = (item) => {
  // 清除可能存在的双击定时器
  clearTimeout(clickTimeout.value);
  // 设置一个标志，表示是单击事件
  clickTimeout.value = setTimeout(() => {
    let { fieldName } = item;
    let arr = rule.data.filter(v => v.field === fieldName);
    currField.value = { ... arr[0] };
  }, 200); // 200毫秒内为单击事件
}
// 是否必填点击
const switchChange = () => {
  let field = currField.value.field;
  for (let i = 0; i < rule.data.length; i++) {
    if(rule.data[i].field === field) {
      rule.data[i].effect.required = currField.value.effect.required;
    }
  }
}
// 保存模板
const saveTemplate = () => {
  if(!templateName.value) return ElMessage({message: '请输入表单名称', type: 'warning' });
  if(!cardType.value) return ElMessage({message: '请选择证件类型', type: 'warning' });
  if(rule.data.length <= 0) return ElMessage({message: '请设置表单字段', type: 'warning' });
  let arr = [];
  rule.data.forEach(v => {
    console.log(v);
    if(v.field === 'datePickers') {
      arr.push({
        fieldName: v.field,
        fieldType:'DatePickers',
        notes: v.title,
        isFlag: v.effect.required ? '0' : '1',
      })
    }else {
      arr.push({
        fieldName: v.field,
        fieldType:v.type,
        notes: v.title,
        isFlag: v.effect.required ? '0' : '1',
      })
    }
  })
  let params = {
    templateName: templateName.value,
    certId:cardType.value,
    fieldTemplateList:arr
  }
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  if(id) {
    params['id'] = id;
    _updateForm(params)
        .then(res => {
          loading.close();
          console.log(res);
          if(res.data.ok) {
            ElMessage({message: '模板修改成功', type: 'success' });
            router.go(-1);
          }
        })
        .catch(err => {
          console.log(err);
          loading.close();
          ElMessage({message: '网络异常', type: 'error' });
        })
  }else {
    _addTemplate(params)
        .then(res => {
          console.log(res);
          loading.close();
          if(res.data.ok) {
            ElMessage({message: '模板保存成功', type: 'success' });
            router.go(-1);
          }
        })
        .catch(err => {
          console.log(err);
          loading.close();
          ElMessage({message: '网络异常', type: 'error' });
        })
  }
}
// 获取详情
const getInfoById = () => {
  const loading = ElLoading.service({lock: true, text: 'Loading', background: 'rgba(0, 0, 0, 0.7)'})
  _getFormInfoById(id)
      .then(res => {
        console.log(res);
        loading.close();
        if(res.data.ok) {
          let item = res.data.data;
          templateName.value = item.templateName;
          cardType.value = item.cert.id;
          let fieldTemplateList = item.fieldTemplateList;
          initFields(fieldTemplateList);
          console.log(fields.value);
          for (let i = 0; i < fieldTemplateList.length; i++) {
            let item = fieldTemplateList[i];
            for (let j = 0; j < fields.value.length; j++) {
              if(fieldTemplateList[i].fieldName === fields.value[j].fieldName) {
                let optionsData = {};
                if(fields.value[j].fieldType === 'select'||fields.value[j].fieldType === 'radio') {
                  optionsData = fields.value[j].optionsData || {};
                }
                let config = addField(item.fieldType,{field:item.fieldName,title:item.notes},optionsData);
                config.effect.required = (item.isFlag === '0')
                rule.data.push(config)
              }
            }
          }
          fApi.value.refreshOptions();
        }
      })
      .catch(err => {
        console.log(err);
        loading.close();
        ElMessage({message: '网络异常', type: 'error' });
      })
}
const initFields = (listFields) => {
  for (let i = 0; i < listFields.length; i++) {
    for (let j = 0; j < fields.value.length; j++) {
      if(listFields[i].fieldName === fields.value[j].fieldName) {
        fields.value[j].select = true;
        continue;
      }
    }
  }
}
</script>
<style scoped lang="scss">
.form-box{
  display: flex;
  user-select: none;
  .form-fields{
    width: 500px;
    border-right: 1px solid #000000;
    padding: 10px;
    .form-fields-item{
      display: inline-block;
      padding: 10px;
      background-color: #ffffff;
      text-align: center;
      margin: 10px;
      width: 130px;
      cursor: pointer;
      border-radius: 2px;
    }
    .form-fields-item:hover{
      background-color: #90c7fd;
    }
  }
  .form-body{
    width: 800px;
    padding: 20px;
  }
  .form-config{
    width: 300px;
    padding: 20px;
    border-left: 1px solid #000000;
    .form-config-item{
      margin-bottom: 10px;
    }
  }
}


.header-title{
  display: flex;
  align-items: center;
  background-color: #ffffff;
  padding: 20px;
}
</style>